import request from  '@/utils/request.js'

// 创建帖子
export const createPostService = (post, coverFiles) => {
    const formData = new FormData();
    formData.append('post', new Blob([JSON.stringify(post)], { type: 'application/json' }));
    if (coverFiles && coverFiles.length > 0) {
        // 支持多图片上传
        if (Array.isArray(coverFiles)) {
            coverFiles.forEach(fileObj => {
                const file = fileObj.file || fileObj; // 兼容不同格式
                formData.append('covers', file);
            });
        } else {
            // 单个文件的情况
            formData.append('cover', coverFiles);
        }
    }
    return request.post('/post/add', formData, {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    });
}

//获取全部帖子
export const getPostAllService = () => {
    return request.get('/post/all')
}

//获取用户帖子列表--分页查询
export const getPostListService = (query) => {
    return request.get('/post/personage', {params:query})
}

//获取用户帖子列表
export const getPostListNoPageService = (userId) => {
    return request.get('/post/list', {params:{userId}})
}

//获取帖子详情
export const getPostDetailService = (id) => {
    return request.get('/post/detail', {params: {id}})
}

//获取板块分类列表
export const getCategoriesListService = () => {
    return request.get('/post/categories')
}

//获取二手/失物帖子类型
export const getPostTypesService = (categoryId) => {
    return request.get('/post/itemType' , {params: {categoryId}})
}

//获取二手/失物帖子列表--分页查询
export const getProductsListService = (query) => {
    return request.get('/post/paging/items', {params: query})
}

//获取二手/失物帖子列表
export const getProductsListsService = (categoryId) => {
    return request.get('/post/items', {params: categoryId})
}

// 增加帖子浏览量
export const incrementPostViewCountService = (id) => {
    return request.post('/post/increment-view/' + id)
}



//获取帖子封面图片
export const getPostCoverService = () => {
    return request.get('/post/cover')
}

//根据帖子id获取封面图片
export const getPostCoverByIdService = (postId) => {
    return request.get('/post/coverById', {params: {postId}})
}

// 获取热门帖子（按浏览量排序）
export const getHotPostsService = () => {
    return request.get('/post/hot')
}

// 修改用户帖子封面
export const updatePostCoverService = (data) => {
    console.log('updatePostCoverService被调用数据:', data);
    
    return request.patch('/post/uploadCover', data, {
        headers: {
            'Content-Type': 'application/json'
        }
    })
}

//修改用户帖子
export const updatePostService = (post) => {
    return request.put('/post/update', post)
}

// 批量更新帖子状态
export const batchUpdatePostStatusService = (postIds, status) => {
    return request.put('/post/batchUpdateStatus', { postIds, status })
}

//删除用户帖子封面
export const deletePostCoverService = (id) => {
    return request.delete('/post/deleteCover', {params: {id}})
}

//删除用户帖子
export const deletePostService = (id) => {
    // 修改为通过query参数传递id
    return request.delete('/post/delete', {params: {id}})
}

